package com.chenhy.server.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chenhy.server.pojo.MailConstants;
import com.chenhy.server.pojo.MailLog;
import com.chenhy.server.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class);

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Autowired
    private IMailLogService mailLogService;

    @Bean
    public Queue queue(){
        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }

    @Bean
    public Binding binding(){
        // 绑定交换机与队列并指定队列的路由key
        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        // 消息确认回调，确认消息到达broker
        // data:消息的唯一标识（UUID），ack:确认结果（布尔值），cause：失败原因
        rabbitTemplate.setConfirmCallback(((data, ack, cause) -> {
            String msgId = data.getId();
            if (ack){
                LOGGER.info("==========>消息发送成功<==============", msgId);
                // 根据msgId到数据库将对应数据更新为发送成功
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 1).eq("msg_id", msgId));
            }else {
                LOGGER.error("==========>消息发送失败<==============", msgId);
            }
        }));

        // 消息失败回调，就是该消息到达broker后如果发送错误比如route匹配queue时匹配不到routerKey时触发
        // msg：消息主题、repCode响应码、repText：响应描述、exchange：交换机、routingKey：路由key
        rabbitTemplate.setReturnCallback((msg, repCode, repText, exchange, routingKey) -> {
            LOGGER.error("==========>消息发送到Queue时失败<==============",msg.getBody());
        });

        return rabbitTemplate;
    }


}
